#!/usr/bin/env python3
# Created by han on 2016/6/9
import time,os,sys,platform,json

if platform.system() == 'Windows':
    BASE_DIR = '\\'.join(os.path.dirname(__file__).split('/')[:-1])
else:
    BASE_DIR = '/'.join(os.path.dirname(__file__).split('/')[:-1])
sys.path.append(BASE_DIR)

from module import public,shop_conf,accout
from conf import db_conf

DB_USER = os.listdir(db_conf.SHOP_DB_BASE)
BANK_USER = os.listdir(db_conf.DB_BASE)



def register():
    """
    初始化用户信息，
    :return: 返回用户信息的字典初始信息
    """
    while True:
        user_name = input("请输入注册的用户名：")
        if user_name and not user_name.isdigit() and len(user_name) > 1:      #用户输入怒能为纯数字，并且长度要大于1位：
            if user_name in DB_USER:                            #如果注册的用户名已经存在，则提示错误
                msg = "这个用户已经存在，请重新输入".center(40," ")
                public.color_msg(31,msg)
                continue
            while True:                                           #对注册时输入金额做判断，不能为空
                user_pass = input("请输入密码： ")
                if not user_pass:
                    msg = "密码不能为空".center(40," ")
                    public.color_msg(31,msg)
                    continue
                else:
                    break
        elif user_name == "b":                              #如果输入b则退出
            msg = " goodbye ".center(35,"=")
            public.color_msg(39,msg)
            break
        else:                                                   #如果输入有误，则提示错误
            msg = "用户名必须是大于【1】位的英文字母且不能为空或【b】退出".center(40," ")
            public.color_msg(31,msg)
            continue
        user_info = {"user": "", "passwd": "","buy_car":{},"pay":{}}
        user_info["user"] = user_name
        user_info["passwd"] = user_pass
        public.save_shop_file(user_name,**user_info)
        msg = "用户{user:*^8s}注册成功".format(user=user_name).center(45," ")
        public.color_msg(32,msg)
        global DB_USER
        DB_USER = os.listdir(db_conf.SHOP_DB_BASE)
        return user_info


def login_info():
    """
    登录接口，提供用户输入用户名密码，并检测
    :return: 用户的信息字典
    """
    while True:
        user_name = input("登录用户名或【b】退出： ")
        if not user_name.isdigit() and user_name:               #判断用户名不为密码，并且为真
            if user_name in DB_USER:                            #判断用户名在db文件中
                user_passwd = input("请输入登录密码： ")
                user_dict = public.load_shop_file(user_name)         #通过load_file取出用户的字典信息,所以日期信息与全局变量没有关系了。
                if user_dict["user"] == user_name and user_dict["passwd"] == user_passwd:       #判断用户的用户名密码
                    print("登陆成功")
                    return user_dict                                        #正确返回用户信息字典
                else:
                    msg = "--用户名或密码有误，请重新输入--".center(40," ")
                    public.color_msg(31,msg)
            elif user_name == "b":
                return False
            else:
                msg = "用户名或密码有误，请重新输入".center(40, " ")
                public.color_msg(31, msg)
        else:
            continue


def shop_outer(func):
    def inner(*arg,**user_dict):
        a = func(*arg,**user_dict)
        user_chose = input("是否进入购物车，【y】进入购物车，【n】继续购物 ：")
        if user_chose == "y":
            public.save_shop_file(a[0],**a[1])
            new_user_dict = check_car(**user_dict)
            pay(**new_user_dict)
        else:
            public.save_shop_file(a[0], **a[1])
            return a
    return inner


def shop(**user_dict):
    while True:
        shelf = [
            ("iphone",4000),
            ("mac",8000),
            ("bike",1000),
            ("pebble",2000)
        ]
        user_chose = public.shop_chose(*shelf)
        if user_chose == "1":
            c = shelf[0]
            return c
        elif user_chose == "2":
            c = shelf[1]
            return c
        elif user_chose == "3":
            c = shelf[2]
            return c
        elif user_chose == "4":
            c = shelf[3]
            return c
        elif user_chose == "c":
            check_car(**user_dict)
        elif user_chose == "0":
            return False

@shop_outer
def buy_car(*arg,**user_dict):
    """
    接受用户选择的物品，做运算
    :param arg: 用户选购的商品
    :param user_dict: 用户信息
    :return: 将商品做运算并添加到购物车字典中
    """
    while True:
        name = arg[0]
        money = arg[1]
        num = input("请输入购买个数： ")
        if not num.isdigit():
            msg = "请输入数字： ".center(40," ")
            public.color_msg(31,msg)
            continue
        num = int(num)
        user_name = user_dict["user"]
        file = db_conf.SHOP_DB_BASE+'/'+user_name
        with open(file,'r',encoding="utf-8") as userr_file:
           user_dict =  public.load_shop_file(file)
        total = money * num
        if name in user_dict["buy_car"]:
            for i in user_dict["buy_car"]:
                # print(i,name,"-----------------")
                if name == i:
                    user_dict["buy_car"][i][1] += num
                    user_dict["buy_car"][i][2] +=total
        else:
           user_dict["buy_car"][name] = [money,num,total]
        return user_name,user_dict


def check_car(**user_dict):
    """
    接收用户登陆时带有用户名的字典并获取已经保存的用户信息字典取得购物车列表
    :param user_dict: 登录时带有用户的字典，获取其用户名
    :return: 返回已经保存好的用户列表，主要目的是将购物车给pay函数使用
    """
    user_name = user_dict["user"]
    user_dict = public.load_shop_file(user_name)
    for i in user_dict["buy_car"]:                      #展示用户的购物车内容
        name = i
        money = user_dict["buy_car"][i][0]
        num = user_dict["buy_car"][i][1]
        all = user_dict["buy_car"][i][2]
        msg = "商品名称：{name}：\n\t单价：{money}\t购买数量：{num}\t金额：{all}\n".format(name=name,money=money,num=num,all=all).center(40," ")
        print(msg)
    return user_dict


def pay(**user_dict):
    """
    接收已经保存好的用户字典，获取其购物车列表，并与信用卡函数配合处理账单。
    :param user_dict: 已经选购好商品的用户字典信息
    :return:
    """
    while True:
        a = time.time()
        b = time.localtime(a)
        TIME = "{year}-{month}-{day} {H}:{M}:{S}".format(year=b.tm_year, month=b.tm_mon, day=b.tm_mday, H=b.tm_hour,
                                                         M=b.tm_min, S=b.tm_sec)
        all_money = 0
        for i in user_dict["buy_car"]:
            all_money += user_dict["buy_car"][i][2]
        print("购物车中商品总价格为：{money:*^10d}".format(money=all_money))
        user_chose = input("是否结账 [y/n] 【n】退出或按【c】清空购物车: ")
        if user_chose == "y":
            #如果信用卡出返回True，表示扣款成功可以执行下面你的操作
            #buy_ret = shop_conf.buy_car(all_money)
            if user_dict["buy_car"] == {}:
                msg = "你没有要结算的商品".center(40," ")
                public.color_msg(33,msg)
                break
            buy_ret = shop_conf.bank_pay(all_money)
            if buy_ret:
                user_name = user_dict["user"]
                buy_car = user_dict["buy_car"]
                user_dict["pay"][TIME] = buy_car
                user_dict["buy_car"] = {}
                db_name = user_dict["user"]
                public.save_shop_file(db_name,**user_dict)
                msg = "购买成功，欢迎您的选购".center(40," ")
                public.color_msg(32,msg)
            #else：说明原因返回以待正时
            else:
                break
        elif user_chose == "n":
            break
        elif user_chose == "c":
            if user_dict["buy_car"] == {}:
                msg = "本来就是空的了，还清？".center(40, " ")
                public.color_msg(33, msg)
                break
            user_inp = input("是否确认清空购物车[y/n]: ")
            if user_inp == "n":
                break
            elif user_inp =="y":
                user_dict["buy_car"] = {}
                public.save_shop_file(user_dict["user"],**user_dict)
                msg = "购物车已清空".center(40," ")
                public.color_msg(32,msg)
                break
            else:
                msg = "输入有误请您重新输入".center(40," ")
                public.color_msg(32,msg)
        else:
            print("输入有误请重新输入")
            continue

def check_pay(**user_dict):
    user_name = user_dict["user"]
    new_user_dict = public.load_shop_file(user_name)
    pay_dict = new_user_dict["pay"]
    if pay_dict == {}:
        msg = "您还没有购买商品".center(40," ")
        public.color_msg(33,msg)
        return False
    for i in pay_dict:
        date = i
        for a in pay_dict[i]:
            name = a
            money = pay_dict[i][a][0]
            num = pay_dict[i][a][1]
            all = pay_dict[i][a][2]
            msg ="      购买日期：\t{date:=^30s}\n商品名称：\t{name}\t\t商品单价\t{money}\t\t购买数量\t\t{num}\t\t总金额\t{all}".format(date=date,name=name,
                                                                                                       money=money,num=num,all=all)
            print(msg)


"""
{"buy_car": {"iphone": [4000, 1, 4000], "bike": [1000, 1, 1000]}, "passwd": "123", "user": "li", "pay": {2015-01-10:["tian",1],}}
"""


def bank_pay(money):
    while True:
        bank_name = input("请您输入信用卡账号： ")
        if bank_name == "b":
            break
        if not bank_name.isdigit() and bank_name:
            if bank_name not in BANK_USER:
                msg = "用户名输入错误： ".center(40," ")
                public.color_msg(31,msg)
                continue
            bank_pass = input("请您输入信用卡密码： ")
            if bank_pass:
                user_dict = public.load_file(bank_name)                 #读取银行信息
                new_user_dict = accout.ret_info(**user_dict)            #将银行信息做一下运算
                if new_user_dict["user"] == bank_name and bank_pass == new_user_dict["passwd"]:   #判断用户名密码相符             #如果密码相符
                    if new_user_dict["lock"] == 3:                          #如果账户被锁定
                        msg = "您的账户已经被锁定，请您联系信用卡管理员解锁".center(40," ")
                        public.color_msg(31,msg)
                        return False                                        #返回错误
                    bank_money = new_user_dict["money"]["avaliable"]        #提取出信用卡中的钱
                    if bank_money >= money:                                 #如果银行中的钱大于等于要买的钱
                        new_user_dict["money"]["avaliable"] -= money        #将信用卡中的钱减去
                        new_user_dict["money"]["unsettled"][1] += money
                        new_user_dict["lock"] = 0
                        accout.ret_info(**new_user_dict)
                        return True                                         #放回为真
                    else:
                        msg = "您的账户余额不足".center(40," ")
                        public.color_msg(31,msg)
                        return False                                        #如果不够就返回错
                else:
                    msg = "用户名或密码不正确请重新输入： ".center(40," ")
                    public.color_msg(31,msg)

        else:
            msg = "输入错误请您重新输入： ".center(40," ")
            public.color_msg(31,msg)
            continue